/**
 * Copy right 2013 by Phan Hoàn Vũ
 * Email hoanvuphan@gmail.com
 */
package vn.universex.parser;

import japa.parser.JavaParser;
import japa.parser.ParseException;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.PackageDeclaration;
import japa.parser.ast.body.ClassOrInterfaceDeclaration;
import japa.parser.ast.visitor.VoidVisitorAdapter;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author Phan Hoan Vu
 * 
 */
public class PackageParser extends VoidVisitorAdapter<Map<String, Set<String>>> {

    private String packageName;

    public void visit(PackageDeclaration n, Map<String, Set<String>> arg) {
        packageName = n.getName().toString();
        if (arg.get(packageName) == null) {
            arg.put(packageName, new HashSet<String>());
        }
    };

    public void visit(ClassOrInterfaceDeclaration n, Map<String, Set<String>> arg) {
        arg.get(packageName).add(n.getName());
    };

    public void visit(File sourceFile, Map<String, Set<String>> result) {
        try (InputStream is = new FileInputStream(sourceFile)) {
            CompilationUnit cu = JavaParser.parse(is);
            new PackageParser().visit(cu, result);
        } catch (IOException | ParseException e) {
            throw new RuntimeException("Error when parse package of file: " + sourceFile.getAbsolutePath(), e);
        }
    }
}
